/*
 * ClienteRMIView.java
 */

package clientermi.ui;

import clientermi.clienteSocket.Registro;
import clientermi.clienteSocket.ClienteSocket;
import clientermi.favoritoRMI.Favorito;
import clientermi.favoritoRMI.BuscadorFavoritos;
import clientermi.favoritoRMI.IBuscadorFavoritos;
import clientermi.controlador.FavoritosControlador;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.ExportException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * The application's main frame.
 */
public class ClienteRMIView extends FrameView {

    private FavoritoForm formaFavorito;
    private ClienteSocket clienteSocket;
    private Registry registro;
    
    public ClienteRMIView(SingleFrameApplication app) {
        super(app);
       // System.setProperty("javax.net.ssl.trustStore", "ssl/miLlavero");
       // System.setProperty("javax.net.ssl.trustStorePassword", "123456");

        initComponents();

        refrescar();
        registro=null;

        ArrayList<String> interfaces = obtenerInterfacesRed();
        for(String interfaz : interfaces){
            this.interfaz.addItem(interfaz);
        }

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ClienteRMIApp.getApplication().getMainFrame();
            aboutBox = new ClienteRMIAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ClienteRMIApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        favoritos = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        puertoRMI = new javax.swing.JTextField();
        registrar = new javax.swing.JButton();
        desconectar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        interfaz = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        ipServidor = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        criterio = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        buscar = new javax.swing.JButton();
        agregar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        numeroResultados = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        favoritos.setName("favoritos"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nombre", "Descripción", "URL"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(clientermi.ui.ClienteRMIApp.class).getContext().getResourceMap(ClienteRMIView.class);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable1.columnModel.title0")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable1.columnModel.title1")); // NOI18N
        jTable1.getColumnModel().getColumn(2).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable1.columnModel.title2")); // NOI18N
        jTable1.getColumnModel().getColumn(3).setResizable(false);
        jTable1.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable1.columnModel.title3")); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        puertoRMI.setText(resourceMap.getString("puertoRMI.text")); // NOI18N
        puertoRMI.setName("puertoRMI"); // NOI18N

        registrar.setText(resourceMap.getString("registrar.text")); // NOI18N
        registrar.setName("registrar"); // NOI18N
        registrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                registrarActionPerformed(evt);
            }
        });

        desconectar.setText(resourceMap.getString("desconectar.text")); // NOI18N
        desconectar.setName("desconectar"); // NOI18N
        desconectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                desconectarActionPerformed(evt);
            }
        });

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        interfaz.setName("interfaz"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        ipServidor.setText(resourceMap.getString("ipServidor.text")); // NOI18N
        ipServidor.setName("ipServidor"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(registrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(desconectar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(6, 6, 6)
                        .addComponent(interfaz, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(jLabel2)
                        .addGap(3, 3, 3)
                        .addComponent(puertoRMI, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(3, 3, 3)
                        .addComponent(jLabel5)
                        .addGap(4, 4, 4)
                        .addComponent(ipServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(interfaz, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(puertoRMI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(ipServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(registrar)
                    .addComponent(desconectar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        favoritos.addTab(resourceMap.getString("jPanel1.TabConstraints.tabTitle"), jPanel1); // NOI18N

        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nombre", "Descripción", "URL"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setName("jTable2"); // NOI18N
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setResizable(false);
        jTable2.getColumnModel().getColumn(0).setPreferredWidth(30);
        jTable2.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable2.columnModel.title0")); // NOI18N
        jTable2.getColumnModel().getColumn(1).setResizable(false);
        jTable2.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable2.columnModel.title1")); // NOI18N
        jTable2.getColumnModel().getColumn(2).setResizable(false);
        jTable2.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable2.columnModel.title2")); // NOI18N
        jTable2.getColumnModel().getColumn(3).setResizable(false);
        jTable2.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable2.columnModel.title3")); // NOI18N

        criterio.setText(resourceMap.getString("criterio.text")); // NOI18N
        criterio.setName("criterio"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        buscar.setText(resourceMap.getString("buscar.text")); // NOI18N
        buscar.setName("buscar"); // NOI18N
        buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarActionPerformed(evt);
            }
        });

        agregar.setText(resourceMap.getString("agregar.text")); // NOI18N
        agregar.setName("agregar"); // NOI18N
        agregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarActionPerformed(evt);
            }
        });

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        numeroResultados.setText(resourceMap.getString("numeroResultados.text")); // NOI18N
        numeroResultados.setName("numeroResultados"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(criterio, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buscar))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(numeroResultados))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
                    .addComponent(agregar))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(buscar, 0, 0, Short.MAX_VALUE)
                    .addComponent(criterio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(numeroResultados))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(agregar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        favoritos.addTab(resourceMap.getString("jPanel2.TabConstraints.tabTitle"), jPanel2); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(favoritos, javax.swing.GroupLayout.PREFERRED_SIZE, 502, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(favoritos, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(clientermi.ui.ClienteRMIApp.class).getContext().getActionMap(ClienteRMIView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 571, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 387, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents
    /**
     * Método de tipo evento que muestra el formulario para ingresar
     * un nuevo favorito
     * @param evt
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        formaFavorito = new FavoritoForm(jTable1);
        formaFavorito.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed
    /**
     * Método de tipo evento que elimina un registro de los mostrados
     * en la tabla
     * @param evt
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int id = (Integer)this.jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        FavoritosControlador controlador = new FavoritosControlador();
        if(controlador.init("sqlite")) {
            controlador.eliminarFavorito(id);
            DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
            modelo.removeRow(jTable1.getSelectedRow());
        }
    }//GEN-LAST:event_jButton2ActionPerformed
    /**
     * Método de tipo evento que valida y permite registrar el cliente
     * @param evt
     */
    private void registrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registrarActionPerformed
        boolean error=false;
        int puerto = 0;
        String interfazRed = obtenerIpInterfaz(this.interfaz.getSelectedItem().toString());
        try{
            puerto=Integer.parseInt(puertoRMI.getText());
            if(puerto < 0 || puerto > 65000){
                throw new NumberFormatException();
            }
        }
        catch(NumberFormatException nfe){
            error=true;
            JOptionPane.showMessageDialog(super.getFrame(), "El puerto debe ser un número entero positivo menor a 65000");
        }

        if(!error){
            try{
                clienteSocket = new ClienteSocket(this.ipServidor.getText().equals("") ? "localhost" : this.ipServidor.getText(),
                        7777);
                if(clienteSocket.init()){
                    if(!interfazRed.equals("")) {
                        String mensaje = clienteSocket.registrar(interfazRed,puerto);
                        if(mensaje.equals("S")){
                            iniciarRMI();
                            JOptionPane.showMessageDialog(super.getFrame(),"Se ha registrado el cliente exitosamente");
                        }
                        else{
                            JOptionPane.showMessageDialog(super.getFrame(), " No se ha registrado el cliente, esto sucede si la combinación de \r\n  ip y el puerto ya esta registrada");
                        }
                    } else {
                        JOptionPane.showMessageDialog(super.getFrame(), "Interface de red no está habilitada");
                    }
                }
                else{
                    JOptionPane.showMessageDialog(super.getFrame(), "No se ha encontrado el servidor de indices");
                    
                }
            }
            catch(ExportException be){
            JOptionPane.showMessageDialog(super.getFrame(), "Ocurrio un error en la conexión, cambie el puerto o \n la interface e intentelo de nuevo");
            clienteSocket.desconectar();
            }
            catch(Exception e){
                JOptionPane.showMessageDialog(super.getFrame(), "La conexión no se realizo, intente de nuevo");
            }
        }
}//GEN-LAST:event_registrarActionPerformed
    /**
     * Método de tipo evento que permite desconectar
     * un cliete socket
     * @param evt
     */
    private void desconectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_desconectarActionPerformed
        clienteSocket.desconectar();
    }//GEN-LAST:event_desconectarActionPerformed

    private void buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarActionPerformed
        ArrayList<Registro> lista = new ArrayList<Registro>();
        if(clienteSocket != null && !criterio.getText().trim().equals("")){
             lista= clienteSocket.construirLista(clienteSocket.obtenerListados());
        }       

        for(Registro registro : lista){
            String nombre="Cliente";
            try{
                Registry registroRMI = LocateRegistry.getRegistry(registro.getIp(),registro.getPuerto());

                IBuscadorFavoritos servicioBuscador = (IBuscadorFavoritos) registroRMI.lookup(nombre);

                ArrayList<Favorito> listaFavoritos = servicioBuscador.buscar(criterio.getText().trim());

                this.numeroResultados.setText(listaFavoritos.size()+"");

                limpiar(jTable2);
                DefaultTableModel modelo = (DefaultTableModel) jTable2.getModel();

                for(Favorito favorito : listaFavoritos){
                    Object[] datos = {favorito.getId(),favorito.getNombre(),favorito.getDescripcion(),favorito.getUrl()};
                    modelo.addRow(datos);
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
}//GEN-LAST:event_buscarActionPerformed
    /**
     * Método de tipo evento que permite agregar un nuevo favorito
     * a la base de datos, por medio del controlador
     * @param evt
     */
    private void agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarActionPerformed
        int indice = jTable2.getSelectedRow();
        if(indice!=-1){
            FavoritosControlador controlador = new FavoritosControlador();
            if(controlador.init("sqlite")){
                Favorito favorito= new Favorito();
                favorito.setNombre((String)jTable2.getValueAt(indice, 1));
                favorito.setDescripcion((String)jTable2.getValueAt(indice, 2));
                favorito.setUrl((String)jTable2.getValueAt(indice, 3));
                controlador.insertarFavorito(favorito);
            }
            controlador.cerrar();
            refrescar();
            //muestra los datos de losf avoritos de base de datos
        }
    }//GEN-LAST:event_agregarActionPerformed

    /**
     * método que refrescar para mostrar el tabla la lista de
     * favoritos que se encuentran dentro de la base de datos
     */
    public void refrescar(){
        FavoritosControlador controlador = new FavoritosControlador();
        ArrayList<Favorito> listaFavoritos= new ArrayList<Favorito>();
        if(controlador.init("sqlite")){
            listaFavoritos = controlador.buscar();
        }
        controlador.cerrar();
        limpiar(jTable1);
        for(Favorito favorito : listaFavoritos){
             //   System.out.println("insertar "+favorito.getId());
                insertar(favorito);

        }
    }
    /**
     * Método que permite la insersión de un nuevo favorito
     * dentro de la tabla que se muestra en pantalla
     * @param favorito
     */
    public void insertar(Favorito favorito){
        javax.swing.table.DefaultTableModel modelo = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        Object[] fila = {favorito.getId(),favorito.getNombre(),favorito.getDescripcion(),favorito.getUrl()};        
        modelo.addRow(fila);
    }
    /**
     * Métodod que permite eliminar todos los registros
     * que se muestran en la tabla que se encuenta en
     * pantall
     * @param tabla
     */
    public void limpiar(JTable tabla){
        javax.swing.table.DefaultTableModel modelo = (javax.swing.table.DefaultTableModel)tabla.getModel();        
        while (modelo.getRowCount()>0){
            modelo.removeRow(0);
        }
    }
    /**
     * Método de inicio y registro de un obgeto RMI
     */
    public void iniciarRMI() throws ExportException {
        String nombre="Cliente";
        try{
            //System.out.println("entro al try");
           // System.setProperty("java.security.policy","servidor.policy"); 
            
            System.setProperty("java.security.policy", "permisos/servidor.policy");
            ///home/estudiante/asdproject/ClienteRMI
            if(System.getSecurityManager()==null){
                System.setSecurityManager(new SecurityManager());
            }
            int puerto = Integer.parseInt(puertoRMI.getText());

			IBuscadorFavoritos servicioBusqueda= new BuscadorFavoritos();
           // System.out.println("definio el objeto remoto");
			IBuscadorFavoritos representante=(IBuscadorFavoritos) UnicastRemoteObject.exportObject(servicioBusqueda,puerto);
           // System.out.println("exporto el objeto"+LocateRegistry.getRegistry(puerto).toString());
            //LocateRegistry.getRegistry(puerto).unbind(nombre);
			if(registro==null){
                registro = LocateRegistry.createRegistry(puerto);
            }          
           
          //  System.out.println("obtuvo registro");
			registro.rebind(nombre,representante);
          //  System.out.println("enlazo");
		//	System.out.println("Se ha logrado colocar en funcionamiento el servidor RMI");
		}
        catch(NumberFormatException nfe){
            System.out.println("Se presento un problema en el registro del servidor, el puerto no es valido ");
        }
        catch(ExportException ee){
            throw new ExportException("");
        }
		catch(Exception e){
			System.out.println("Se presento un problema en el registro del servidor "+e.getMessage());
            e.printStackTrace();
		}
    }

    public ArrayList<String> obtenerInterfacesRed(){
        ArrayList<String> interfaces = new ArrayList<String>();
        try{
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)){
                if(netint.isUp())
                    interfaces.add(netint.getName());
               /* Enumeration<InetAddress> lista = netint.getInetAddresses();
                for(InetAddress direccion : Collections.list(lista)){
                    System.out.println("dato "+direccion.getHostAddress());
                }*/
               // System.out.println(netint.getInetAddresses().nextElement().getHostAddress());
            }
        }
        catch (Exception e){
            System.out.println("Error al obtener las interfaces de red");
        }
        return interfaces;
    }

    public String obtenerIpInterfaz(String nombre){
        try{
            NetworkInterface interfazRed = NetworkInterface.getByName(nombre);
            if(Collections.list(interfazRed.getInetAddresses()).size() > 1) {
                return (Collections.list(interfazRed.getInetAddresses()).get(1)).getHostAddress();
            }
        }
        catch(IOException ioe){

        }
        return "";
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregar;
    private javax.swing.JButton buscar;
    private javax.swing.JTextField criterio;
    private javax.swing.JButton desconectar;
    private javax.swing.JTabbedPane favoritos;
    private javax.swing.JComboBox interfaz;
    private javax.swing.JTextField ipServidor;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JLabel numeroResultados;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JTextField puertoRMI;
    private javax.swing.JButton registrar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}
